<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    /**
 * @param {number[][]} mat
 * @return {number[][]}
 * 思路：原数组是0的，新数组都为0；然后遍历新数组，-1时当前值+1
 * 输入：mat = [[0,0,0],[0,1,0],[0,0,0]]
 * 输出：[[0,0,0],[0,1,0],[0,0,0]]
 * 
 * 输入：mat = [[0,0,0],[0,1,0],[1,1,1]]
 * 输出：[[0,0,0],[0,1,0],[1,2,1]]
 */
    var updateMatrix = function (mat) {
      let m = mat.length, n = mat[0].length
      let res = new Array(m).fill('.').map(item => new Array(n).fill(-1))
      let p = []
      let dirs = [[0, 1], [0, -1], [1, 0], [-1, 0]]
      for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
          if (mat[i][j] === 0) {
            res[i][j] = 0
            p.push([i, j])
          }
        }
      }

      while (p.length > 0) {
        let sz = p.length
        for (let i = 0; i < sz; i++) {
          let cur = p.shift()
          for (let j = 0; j < dirs.length; j++) {
            let x = cur[0] + dirs[j][0]
            let y = cur[1] + dirs[j][1]
            if (x >= 0 && y >= 0 && x < m && y < n && res[x][y] === -1) {
              res[x][y] = res[cur[0]][cur[1]] + 1
              p.push([x, y])
            }
          }
        }

      }
      return res
    };
    console.log(updateMatrix([[0, 0, 0], [0, 1, 0], [1, 1, 1]]));
  </script>
</body>

</html>